package com.example.miscontactos;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.example.miscontactos.Entidades.Contacto;
import com.example.miscontactos.Entidades.NombreAccion;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.Contacts;
import android.app.Activity;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextWatcher;

public class ListaContactos extends ListActivity
{
	private static final int LLAMAR_TEL = 0;
	private static final int MENSAJE_TEL = 1;
	private static final int MAIL = 2;
	private static final int MENSAJE_WEB = 3;
	ArrayList<String> phones = null;
	ArrayList<String> emails = null;
	private String contactoId;
	private SharedPreferences preferencias;
	ArrayAdapter<String> adapter = null;
	private static String CONTACTO_ID = "contactoId";

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        registerForContextMenu(getListView());
        
        phones = null;
        
        cargarContactos();
    }

	private void cargarContactos() 
	{
		String orden = getOrden();
        
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " " + orden);
             
        ListAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cur, 
        		new String[] { ContactsContract.Contacts.DISPLAY_NAME }, new int[] { android.R.id.text1 });
        
        setListAdapter(adapter);
	}
    	
    private String getOrden()
	{
		String orden = "";
		preferencias = PreferenceManager.getDefaultSharedPreferences(this);
		Boolean asc = preferencias.getBoolean("orden_contacto", true);
		
		if (asc)
		{
			orden = "ASC";
		}
		else 
		{
			orden = "DESC";
		}
		
		return orden;
	}
    
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id)
    {
    	Intent intent = new Intent(this, PerfilContacto.class);
    	intent.putExtra(CONTACTO_ID, id);
    	startActivity(intent);
    }
    
    @Override
	protected void onResume() 
	{
	    super.onResume();
	    cargarContactos();
	}
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
    	menu.add(Menu.NONE, 0, 0, getResources().getString(R.string.menu_preferencias));
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
    	switch (item.getItemId()) 
    	{
    		case 0:
    			Intent intent = new Intent(ListaContactos.this, Preferencias.class);
    	    	startActivity(intent);
                return true;
        }
        return false;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) 
    {    	   	
    	String nroTel = "";
        switch (item.getItemId()) 
        {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                break;
            case LLAMAR_TEL:
            	nroTel = phones.get(0);
            	AccionesUtilities.LlamarContacto(this, contactoId, nroTel, "", "", NombreAccion.Llamada, "");
            	break;
            case MENSAJE_TEL:
            	nroTel = phones.get(0);
            	AccionesUtilities.MandarMensaje(this, contactoId, nroTel, "", "", NombreAccion.Mensaje, "");
            	break;
            case MAIL:
            	AccionesUtilities.MandarEmail(this, contactoId, "", emails.get(0), "", NombreAccion.Mail, "");
        }
        return true;
    }
    
    //Metodo que se llama para crear el menu contextual.
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
    {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		menu.clear();
		menu.setHeaderTitle(getResources().getString(R.string.titulo_menu_contextual));
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
		phones = this.GetContactInformation(info.position);
		Boolean tieneInfo = false;
		if(phones.size() > 0)
		{
			menu.addSubMenu(0, LLAMAR_TEL, 0, getResources().getString(R.string.sub_menu_contextual_llamada) + phones.get(0));
			menu.addSubMenu(0, MENSAJE_TEL, 0, getResources().getString(R.string.sub_menu_contextual_mensaje) + phones.get(0));
			tieneInfo = true;
		}
		
		emails = this.GetContactEmails(info.position);
		if(emails.size() > 0)
		{
			menu.addSubMenu(0, MAIL, 0, getResources().getString(R.string.sub_menu_contextual_mail) + emails.get(0));
			tieneInfo = true;
		}		
		if(!tieneInfo)
		{
			menu.close();
			Toast toast = Toast.makeText(this, getResources().getString(R.string.menu_contextual_vacio), Toast.LENGTH_SHORT);
			toast.show();
		}
		inflater.inflate(R.menu.contact_menu, menu);
	}
        
    private String GetContactId(int position)
    {
    	Cursor cursor = (Cursor) getListView().getItemAtPosition(position);
    	return cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
    }
    
    private ArrayList<String> GetContactInformation(int position)
    {
    	Cursor cursor = (Cursor) getListView().getItemAtPosition(position);
        contactoId = cursor.getString(cursor.getColumnIndexOrThrow( ContactsContract.Contacts._ID));
        return getPhoneNumbers(contactoId);
    }
    
    private ArrayList<String> GetContactEmails(int position)
    {
    	Cursor cursor = (Cursor) getListView().getItemAtPosition(position);
        String contactId = cursor.getString(cursor.getColumnIndexOrThrow( ContactsContract.Contacts._ID));
        return getEmails(contactId);
    }
    
    private ArrayList<String> getPhoneNumbers(String id) 
    {
        ArrayList<String> phones = new ArrayList<String>();

        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(
                CommonDataKinds.Phone.CONTENT_URI, 
                null, 
                CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                new String[]{id}, null);

        while (cursor.moveToNext()) 
        {
            phones.add(cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER)));
        } 

        cursor.close();
        return(phones);
    }
    
    private ArrayList<String> getEmails(String id) 
    {
        ArrayList<String> emails = new ArrayList<String>();
        
        ContentResolver cr = getContentResolver();        
        Cursor cursor = cr.query(
                CommonDataKinds.Email.CONTENT_URI, 
                null, 
                CommonDataKinds.Phone.CONTACT_ID +" = ?", 
                new String[]{id}, null);

        while (cursor.moveToNext()) 
        {
            emails.add(cursor.getString(cursor.getColumnIndex(CommonDataKinds.Email.ADDRESS)));
        } 

        cursor.close();
        return(emails);
    }

    @Override
    public Dialog onCreateDialog(int id)
    {
    	Dialog dialogo = null;
    	
    	return dialogo;
    }
    
}
